import { useState, useRef } from 'react'
import { LinkIcon, Download1Icon } from 'tdesign-icons-react'
import { Upload, Link } from 'tdesign-react'
import { html } from 'diff2html'
import * as Diff from 'diff'
import 'diff2html/bundles/css/diff2html.min.css'

import './index.less'

export default function Home() {
  const [files] = useState([])
  const [downloadName, setDownloadName] = useState('')
  const [downloadLink, setDownloadLink] = useState('')
  const diffRef = useRef<HTMLDivElement>(null)

  const convertHtml = (file: File) => {
    const reader = new FileReader()
    reader.readAsText(file)
    reader.onload = async (event) => {
      const originalHtml = event.target?.result
      if (!originalHtml) {
        return
      }
      const parser = new DOMParser()
      const doc = parser.parseFromString(originalHtml as string, 'text/html')
      const images = doc.querySelectorAll('img')

      for (const img of images) {
        const url = img.src
        const response = await fetch(url)
        const blob = await response.blob()
        try {
          const base64 = await convertBlobToBase64(blob)
          if (!base64) {
            return
          }
          img.src = base64
        } catch (error) {
          console.error('Error converting image:', error)
        }
      }
      // 创建新的HTML字符串
      const newHtml = `<!doctype html>` + doc.documentElement.outerHTML

      // 生成HTML文件并下载
      const blob = new Blob([newHtml], { type: 'text/html' })

      // Create a download link
      setDownloadLink(URL.createObjectURL(blob))
      setDownloadName(`${file.name}_b64.html`)
      showDiff({ name: file.name, value: originalHtml as string }, { name: `${file.name}_b64.html`, value: newHtml })
    }
  }

  const convertMd = (file: File) => {
    const reader = new FileReader()
    reader.readAsText(file)
    reader.onload = (event) => {
      const md = event.target?.result
      console.log(md)
      // TODO 现在用不到，以后再补充
    }
  }

  interface IdiffFile {
    name: string
    value: string
  }
  const showDiff = (origin: IdiffFile, updated: IdiffFile) => {
    const diff = html(Diff.createTwoFilesPatch(origin.name, updated.name, origin.value, updated.value), {
      drawFileList: false,
    })
    if (diffRef.current) {
      diffRef.current.innerHTML = diff
    }
  }

  const fileSelect = (files: File[]) => {
    const file = files[0]
    const fileName = file.name
    const fileExtension = fileName.slice(fileName.lastIndexOf('.')).toLowerCase()
    // 如果是html文件
    if (file.type === 'text/html') {
      convertHtml(file)
    }

    // 如果是md文件
    if (file.type === 'text/markdown' || fileExtension === '.md') {
      convertMd(file)
    }
  }

  const convertBlobToBase64 = (blob: Blob) => {
    return new Promise((resolve: (value: string) => void, reject) => {
      const reader = new FileReader()
      // debugger
      reader.readAsDataURL(blob)
      reader.onloadend = () => {
        if (!reader.result) {
          reject(new Error('reader.result 不存在'))
        }
        resolve(reader.result as string)
      }
      reader.onerror = reject
    })
  }

  return (
    <div className="index-component">
      <h1>Convert HTML Images to Base64</h1>
      <Link href="https://gitee.com/yishen_yishen/html-net-img2-base64" theme="default" prefixIcon={<LinkIcon />}>
        项目介绍
      </Link>
      <Upload draggable theme="file" files={files} onSelectChange={fileSelect} autoUpload={false} accept="text/html,.md"></Upload>
      {downloadLink && (
        <Link
          href={downloadLink}
          size="large"
          // @ts-ignore
          download={downloadName}
          target="_self"
          theme="default"
          prefixIcon={<Download1Icon />}
        >
          Download Converted HTML
        </Link>
      )}
      <div ref={diffRef}></div>
    </div>
  )
}
